from PyQt5.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QLineEdit, QMessageBox
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class AddRecordDialog(QDialog):
    def __init__(self, parent, current_ledger, refresh_table, update_stats):
        super().__init__(parent)
        self.setWindowTitle("添加新记录")
        self.current_ledger = current_ledger
        self.refresh_table = refresh_table
        self.update_stats = update_stats
        self.setup_ui()

    def setup_ui(self):
        fields = [
            ('姓名', 'name'),
            ('金额', 'amount'),
            ('关系', 'relationship'),
            ('场合', 'occasion'),
            ('备注', 'notes')
        ]

        layout = QVBoxLayout()
        self.entries = {}
        for label, key in fields:
            h_layout = QHBoxLayout()
            h_layout.addWidget(QLabel(label + ":"))
            entry = QLineEdit()
            h_layout.addWidget(entry)
            self.entries[key] = entry
            layout.addLayout(h_layout)

        save_button = QPushButton("保存")
        save_button.clicked.connect(self.save_record)
        layout.addWidget(save_button)

        self.setLayout(layout)

    def save_record(self):
        data = {}
        try:
            for key, entry in self.entries.items():
                value = entry.text()
                if key == 'amount':
                    value = float(value)
                data[key] = value

            self.current_ledger.add_record(data)
            self.refresh_table()
            self.update_stats()
            self.close()
            QMessageBox.information(self, "成功", "记录添加成功！")
            logging.info("Successfully added a new record")
        except ValueError:
            QMessageBox.critical(self, "错误", "金额必须为数字")
            logging.error("Failed to add a new record: Amount must be a number")


class EditRecordDialog(QDialog):
    def __init__(self, parent, current_ledger, refresh_table, update_stats, record_id):
        super().__init__(parent)
        self.setWindowTitle("编辑记录")
        self.current_ledger = current_ledger
        self.refresh_table = refresh_table
        self.update_stats = update_stats
        self.record_id = record_id
        original_data = next(r for r in current_ledger.records if r['id'] == record_id)
        self.setup_ui(original_data)

    def setup_ui(self, original_data):
        fields = [
            ('姓名', 'name'),
            ('金额', 'amount'),
            ('关系', 'relationship'),
            ('场合', 'occasion'),
            ('备注', 'notes')
        ]

        layout = QVBoxLayout()
        self.entries = {}
        for label, key in fields:
            h_layout = QHBoxLayout()
            h_layout.addWidget(QLabel(label + ":"))
            entry = QLineEdit()
            entry.setText(str(original_data.get(key, '')))
            h_layout.addWidget(entry)
            self.entries[key] = entry
            layout.addLayout(h_layout)

        update_button = QPushButton("更新")
        update_button.clicked.connect(self.update_record)
        layout.addWidget(update_button)

        self.setLayout(layout)

    def update_record(self):
        new_data = {}
        try:
            for key, entry in self.entries.items():
                value = entry.text()
                if key == 'amount':
                    value = float(value)
                new_data[key] = value

            if self.current_ledger.update_record(self.record_id, new_data):
                self.refresh_table()
                self.update_stats()
                self.close()
                QMessageBox.information(self, "成功", "记录更新成功！")
                logging.info(f"Successfully updated record with ID {self.record_id}")
        except ValueError:
            QMessageBox.critical(self, "错误", "金额必须为数字")
            logging.error(f"Failed to update record with ID {self.record_id}: Amount must be a number")


class LedgerSelectorDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("选择账本")
        self.setGeometry(300, 300, 300, 150)
        self.selected_ledger = None
        self.setup_ui()

    def setup_ui(self):
        layout = QVBoxLayout()
        layout.addWidget(QLabel("请选择要管理的账本类型"))

        button_layout = QHBoxLayout()

        send_button = QPushButton("随礼账本")
        send_button.clicked.connect(lambda: self.select_ledger("send"))
        button_layout.addWidget(send_button)

        receive_button = QPushButton("收礼账本")
        receive_button.clicked.connect(lambda: self.select_ledger("receive"))
        button_layout.addWidget(receive_button)

        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(cancel_button)

        layout.addLayout(button_layout)

        self.setLayout(layout)

    def select_ledger(self, ledger_type):
        self.selected_ledger = ledger_type
        self.accept()